package com.zijie.pay.controller;



import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 喻字杰与刘宝宝
 */
@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {
       final  String  notifyUrl="http://bf7ee383.natappfree.cc/alipay/notify";
   final String returnUrl="http://bf7ee383.natappfree.cc";
    private static AlipayConfig getAlipayConfig() {
        String privateKey  = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfAg35HaqXDJJD9lZgPxVN4g6RyOVeUTFQkXtH/PEG0YF+Yk01ceOsvcTfZiqRDYikfaNQdpDXB62vha3M/yWTWIQ/F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Wbmn8+HXExL8Ja0Z75fHVlQGpyBRrcQCYcVJvBdAoGAXdTaPCCDAchrEIFNSjucBgFD80KP1OiyYvlUW0iiQomi8UxuII+DWgKosyRUpmf8+ljwWR7arftzDHWeG9IxVzq3KMDO2qNmi23t6fLrUOOQOsorm6FVp8KadBjlhiPHuqXfQvgeqHsg/Mdy/Em8XD9QihYKOCbOdb9o7V2j2mECgYEAyrOftbOjhIY+UpppMGgkNrdy5cbnKl6Nh1F+Sd8RWdkgSkSFwSyRy3JObqeAWHVaMWsWFpKdOZ1F0i3lzlWEvHLCaXfMJCu5npkuFDhOwzI7a5Wq/SxcFSgYpmqpPrD6OnKjZvyLM2DDqEN5vJ8V467Qc2AnHS0xWZcRwujPY9s=";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhyJzvVv7cIOQgX/Ewb219xZ36QVFcDWLNeNvfE+0tX3u+io9FSv0SZzO1tC23JCrqATLZ7fzHT4ypcrnba791sz9opI6iwLg8NsZC5tD1LDgU2xlNdB8Vl6MGmyVL4ZSaRPOm7wKkhW4Klpm5OC0nfhIIw3HSYDR+3EWpc1Y2a/5CbvJJ8ug9qUvqE89Yd+r53JCFwgF2l5B0UBt9ghTOLiKrK2P+wfeioW5WjTDU5pznujDe6NzpjseagWrWOXsEVNhXyuN7CfHyrxxmtxnqlAlZNfdFOOJ8YlwvJLpDF8C+rT5SVoZ7S87SrY/dVtuVEsGzbvRzNRdDD7CHoOK9QIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("2021000149603050");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    public static void disableSslVerification() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final String CHARSET ="utf-8";

    //支付宝电脑网站支付
    @SaIgnore
    @GetMapping("/pay") //
    public void pay(String subject ,String totalAmount , HttpServletResponse httpResponse) throws Exception {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        String orderNo = IdUtil.simpleUUID();
        System.out.println("订单号=>"+orderNo);
        // 设置商户订单号
        model.setOutTradeNo(orderNo);
        // 设置订单总金额
        model.setTotalAmount(totalAmount);

        // 设置订单标题
        model.setSubject(subject);

        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置PC扫码支付的方式
        //model.setQrPayMode("1");


        request.setBizModel(model);
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        String form="";
        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
            // 如果需要返回GET请求，请使用
            // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
            form= response.getBody();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    //支付宝电脑查询订单状态网站支付
    @SaIgnore
    @GetMapping("/getAlipayOutTradeNo") //
    public String getAlipayOutTradeNo(String out_trade_no) throws Exception {
// 初始化SDK
        disableSslVerification();
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(out_trade_no);


        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String body = response.getBody();
            System.out.println(body);
            try {
                // 解析根对象
                JSONObject root = JSONObject.parseObject(body);

                // 获取响应数据对象
                JSONObject responsedata = root.getJSONObject("alipay_trade_query_response");

                // 提取所需字段
                String code = responsedata.getString("code");
                if ("10000".equals(code)){
                    String sendPayDate = responsedata.getString("send_pay_date");
                    String totalAmount = responsedata.getString("total_amount");;
                    String tradeStatus = responsedata.getString("trade_status");

                    // 输出结果
                    System.out.println("code: " + code);
                    System.out.println("send_pay_date: " + sendPayDate);
                    System.out.println("total_amount: " + totalAmount);
                    System.out.println("trade_status: " + tradeStatus);
                    return tradeStatus;
                }
                else {
                    return "交易不存在";
                }




            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";
    }

//退款
    @SaIgnore
    @GetMapping("/refund")  // 注意这里必须是POST接口
    public String refund(String out_trade_no,String refund_amount) throws Exception {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();

        // 设置商户订单号
        model.setOutTradeNo(out_trade_no);
        // 设置退款金额
        model.setRefundAmount(refund_amount);
        // 设置退款原因说明
        model.setRefundReason("正常退款");
        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        AlipayTradeRefundResponse response = alipayClient.execute(request);
       return  response.getBody();
        }
//查询退款
    @SaIgnore
    @GetMapping("/refundQuery")  // 注意这里必须是POST接口
    public String refundQuery(String out_trade_no) throws Exception {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();



        // 设置商户订单号
        model.setOutTradeNo(out_trade_no);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
return  response.getBody();


    }



//支付回调
    @SaIgnore
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {

        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhyJzvVv7cIOQgX/Ewb219xZ36QVFcDWLNeNvfE+0tX3u+io9FSv0SZzO1tC23JCrqATLZ7fzHT4ypcrnba791sz9opI6iwLg8NsZC5tD1LDgU2xlNdB8Vl6MGmyVL4ZSaRPOm7wKkhW4Klpm5OC0nfhIIw3HSYDR+3EWpc1Y2a/5CbvJJ8ug9qUvqE89Yd+r53JCFwgF2l5B0UBt9ghTOLiKrK2P+wfeioW5WjTDU5pznujDe6NzpjseagWrWOXsEVNhXyuN7CfHyrxxmtxnqlAlZNfdFOOJ8YlwvJLpDF8C+rT5SVoZ7S87SrY/dVtuVEsGzbvRzNRdDD7CHoOK9QIDAQAB", CHARSET, AlipayConstants.SIGN_TYPE_RSA2);
            //调用SDK验证签名
            // 支付宝验签
            if (signVerified) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单状态

            }else {
               return  "failure";
            }
        }
        return "success";
    }
}
